Python Interview Questions and Answers
Prepare for your Interview today!
In Python programming, the class is created using a class keyword. The syntax for creating a class is as follows:
Example:
class ClassName:
code statement
The syntax for creating an instance of a class is as follows:
<object-name> = <class-name>(<arguments>)
The Method is defined as the function associated with a particular object. The method which we define should not be unique as a class instance. Any type of object can have methods.
Many people used to C or Perl complain that they want to use this C idiom: while (line = readline(f)) {
...do something with line...
}
where in Python you're forced to write this:
while True:
line = f.readline() if not line:
break
...do something with line...
The reason for not allowing assignment in Python expressions is a common, hard-to-find bug in those other languages, caused by this construct:
if (x = 0) {
...error handling...
}
else {
...code that only works for nonzero x...
}
The error is a simple typo: x = 0, which assigns 0 to the variable x, was written while the comparison x == 0 is certainly what was intended.
Many alternatives have been proposed. Most are hacks that save some typing but use arbitrary or cryptic syntax or keywords, and fail the simple criterion for language change proposals: it should intuitively suggest the proper meaning to a human reader who has not yet been introduced to the construct.
x = 1 # make a global
def f():
print x # try to print the global
for j in range(100):
if q>3:
x=4
Any variable assigned in a function is local to that function. unless it is specifically declared global. Since a value is bound to x as the last statement of the function body, the compiler assumes that x is local. Consequently, the print x attempts to print an uninitialized local variable and will trigger a NameError.
The solution is to insert an explicit global declaration at the start of the function:
def f():
global x
print x # try to print the global
for j in range(100):
if q>3:
x=4
In this case, all references to x are interpreted as references to the x from the module namespace.
Most helpful rated by users: